package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.exception.ComFoundException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Result login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(user.getUsername() != null, "username", user.getUsername());
        User users = userMapper.selectOne(queryWrapper);
        // 通过用户名从数据库中查询出该用户
        if (users == null) {
            throw new ComFoundException("用户名不存在");
        }
        // 密码校验
        String s = (MD5Utils.md5(user.getPassword() + users.getSalt()));
        if (users.getPassword().equals(s) == false) {
            throw new ComFoundException("密码不正确");
        }
        UserDTO userDTO = new UserDTO(user.getId(),user.getUsername(),user.getImgUrl());
        String token = JwtUtils.generateToken(userDTO);
        return Result.ok().data("token", token).data("id",users.getId()).data("username",users.getUsername()).data("imgUrl",users.getImgUrl());
    }

    @Override
    public Result logOut(User user) {
        return null;
    }

    @Override
    public Result register(User user) {
        try {
            // 查询用户名是否存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            User users = userMapper.selectOne(queryWrapper);
            if (users != null) {
                throw new ComFoundException("用户已经存在");
            }
            // 设置盐
            String salt = UUIDUtils.getUUID();
            user.setSalt(salt);
            // 设置密码加密
            String s = MD5Utils.md5(user.getPassword() + salt);
            // 设置用户默认头像
            user.setImgUrl("https://pixabay.com/get/ga6cfd3a04106d2da5488e446c15827225457b21925bda8b777e5471a02fe14ea580ec9cf9153a559e1f142e7f17bd68e6aa8bf302a46eb24a6f775248bf4212ae0d0a83e7ade64538991e706582c3d8b_1280.png");
            user.setPassword(s);
            int insert = userMapper.insert(user);
            if (insert>0){
                return Result.ok().data("成功", ResultCode.SUCCESS);
            }else {
                return Result.error().data("系统繁忙", ResultCode.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().data("失败", ResultCode.ERROR);
        }
    }
}